import webapp2
from Model import *
from datetime import *
from google.appengine.ext import ndb
import logging
from NotificationsUtils import *

timedifference = 3

class StartRaceHandler(webapp2.RequestHandler):

    def post(self):
        race_key = ndb.Key('Race',int(self.request.POST.get('key')))
        #logging.info('Race key',str(self.request.POST.get('key')))
        race = race_key.get()
      #  logging.info("Race part",str(race.Participants))

        data = {"Key": self.request.POST.get('key'),'messageType':'RACE_STARTING' ,'Estimated':race.EstimatedTime,"Tags":race.Tags,"Distance":race.Distance,"numofparticipants":len(race.ReadyParticipants)}#"Time":race.StartTime}#"Manager":race.Manager,"Participants":race.ReadyParticipants}
        logging.info(data)
        race = race_key.get()
        res = sendMessageToClients(messageType = 'RACE_STARTING',registration_ids = [x.get().RegID for x in race.ReadyParticipants] ,data=data )
        race.Status = RaceStatus.During
        race.LiveUsersNumber = len(race.ReadyParticipants)
        race.put()



    def get(self):
        logging.info(str(datetime.utcnow()))
        races = Race.query(ndb.AND(Race.Status == RaceStatus.Before, Race.StartTime <= datetime.utcnow()+ timedelta(hours=timedifference)))

        for race in races:
            logging.info(str(race.StartTime))

            logging.info(race.key.id())
         #   if race.Generation == RaceGenerate.Auto:
            if len(race.ReadyParticipants) > 0:
                startRace(race)
            else:
                race.Status = RaceStatus.Finished
                race.key.delete()
            #else:
                #if race.StartTime <= datetime.utcnow()+ timedelta(hours=2) -timedelta(minutes=2) and race.Manager not in race.ReadyParticipants:
                 #   startRace(race)
             #   if race.StartTime <= datetime.utcnow() + timedelta(hours=2) - timedelta(minutes=2):
              #      startRace(race)

        races = Race.query(ndb.AND(Race.Status == RaceStatus.Before, Race.StartTime <= datetime.utcnow()+ timedelta(hours=timedifference) + timedelta(minutes=61), Race.StartTime > datetime.utcnow()+ timedelta(hours=timedifference) + timedelta(minutes=59)))
        for race in races:

            data = {'messageType':'RACE_IN_ONE_HOUR'}
            data.update({"Key": race.key.id(), "Manager": race.Manager.get().Name,\
                        "Distance": race.Distance, "Time": str(race.StartTime),\
                        "Tags" : race   .Tags, "Participants":race.NumOfParticipants,\
                        "ManagerId": race.Manager.id(), "Estimated":race.EstimatedTime})
            logging.info(data)
            res = sendMessageToClients(messageType = 'RACE_IN_ONE_HOUR',registration_ids = [x.get().RegID for x in race.Participants] ,data=data )


#'APA91bHY41S3zREKVP3Pk4RLZzYRn5qMVDJgUTfUhpk_BDIq5AThOOnDaN0nVJfIR9M9aVIb1ThJn60aO2m2bTg6vu6lcCnCX-ss_0Stt5RVZ53GE4j8y86BnDvCgnxN-q89dLFbcT3vc8JVM-2RS4at3muRkkrZ3Q'
#[x.get().RegID for x in race.Participants]


def startRace(race):
    data = {"Key": race.key.id(),'messageType':'RACE_STARTING' ,'Estimated':race.EstimatedTime, "Tags":race.Tags,"Distance":race.Distance,"numofparticipants":len(race.ReadyParticipants)}
    logging.info(data)
    registration_ids = []
    for racer_key in race.ReadyParticipants:
        racer = racer_key.get()
        if not 'dummy' in racer.Email:
            registration_ids.append(racer.RegID)
    logging.info(registration_ids)
    if len(registration_ids) > 0:
        res = sendMessageToClients(messageType = 'RACE_STARTING',registration_ids = [x.get().RegID for x in race.ReadyParticipants if not 'dummy' in x.get().Email] ,data=data )
        race.Status = RaceStatus.During
    else:
        race.Status = RaceStatus.Finished
    race.LiveUsersNumber = len(race.ReadyParticipants)
    race.put()